<?php
/*
Auth:Sang
Desc:后台用户模型
Date:2014-10-27
*/
namespace Mod;
use Lib\Model;
use Lib\Common;
use Lib\Encrypt;
class User extends Model{
	public function isLogin(){
		if(!session('uid')){
			$user_id=$this->getCookieRemember();
			if($user_id>0){
				$this->loginDoSomething($user_id);
				return true;
			}
			return false;
		}
		return session('uid');
	}

	public function login($username,$password){
		$user_info = $this->where("user_name='{$username}'")->limit(1)->fetch();
		if(!empty($user_info) && $this->genPassword($password,$user_info['salt'])[0]==$user_info['password']){
			$this->loginDoSomething($user_info['user_id']);
			return $user_info;
		}
		return false;
	}

	public function loginDoSomething($user_id){
		$user_info = $this->getUserById($user_id);
		if($user_info['status']!=1){
			return redirect('/os/login');
		}

		$user_group = model('#UserGroup','adm_')->getGroupById($user_info['user_group']);
		$user_info['group_id']=$user_group['group_id'];
		$user_info['user_role']=$user_group['group_role'];
		$user_info['shortcuts_arr']=explode(',',$user_info['shortcuts']);
		$user_info['setting']=0;
		$menu = model('#MenuUrl','adm_')->getMenuByUrl('/os/setting');
		if((isset($menu['menu_id']) && strpos($user_group['group_role'],$menu['menu_id'])) || $user_info['user_id']==1){
			$user_info['setting']=1;
		}
		
		//更新登录信息
		$login_time = time();
		$login_ip = Common::getIp ();
		$this->where("user_id='{$user_info['user_id']}'")->update(array ('login_ip' => $login_ip, 'login_time' => $login_time ));
		$user_info['login_ip']=$login_ip;
		$user_info['login_time']=Common::getDateTime($login_time);
		unset($user_info['password'],$user_info['salt']);
		$this->setSession($user_info);
	}

	public function reloadSession(){
		$user_info = $this->getUserById(session('uid'));
		if($user_info['status']!=1){
			redirect('/os/login');
			return false;
		}
		
		//读取该用户所属用户组将该组的权限保存在$_SESSION中
		$user_group = model('#UserGroup','adm_')->getGroupById($user_info['user_group']);
		$user_info['group_id']=$user_group['group_id'];
		$user_info['user_role']=$user_group['group_role'];
		$user_info['shortcuts_arr']=explode(',',$user_info['shortcuts']);
		$user_info['setting']=0;
		$menu = model('#MenuUrl','adm_')->getMenuByUrl('/os/setting');
		if((isset($menu['menu_id']) && strpos($user_group['group_role'],$menu['menu_id'])) || $user_info['user_id']==1){
				$user_info['setting']=1;
			}
		unset($user_info['password'],$user_info['salt']);
		$this->setSession( $user_info);
		return true;
	}

	public function setSession($user){
		session('uid',$user['user_id']);
		session('user_info',$user);
		cookie('_adm',urlencode(Encrypt::encrypt($user['user_id'])));
	}

	public function loginOut(){
		session(null);
		cookie('adm_remember',null);
		cookie('_adm',null);
	}

	/**
   * 产生密码  双重MD5 加扰码
   * @param string $password
   * @return Array
   */
  public function genPassword($password,$salt=''){
    $salt or $salt = substr(uniqid(rand()), -6);
    return array(md5(md5($password).$salt),$salt);
  }

  public function checkPassword($user_name, $password) {
  	$user = $this->where("user_name = '{$user_name}'")->fetch();
  	list($gen_password,$salt) = $this->genPassword($password,$user['salt']);
  	if($gen_password != $user['password']){
  		return false;
  	}
  	return true;
}

  public function setTemplate($t){
  	if($this->where("user_id=".session('uid'))->update(array('template'=>$t))){
	  	$user_info = session('user_info');
	  	$user_info['template'] = $t;
	  	session('user_info',$user_info);
	  }
  }

  public function getTemplate(){
  	return isset(session('user_info')['template']) && !empty(session('user_info')['template']) ? session('user_info')['template'] : 'default';
  }

  public function getSidebar(){
  	$user_info = session('user_info');
  	if(empty($user_info)){
  		return;
  	}
	//功能菜单
	$data = model('#Module','adm_')->getAllModules(1);
	//用户的权限
	$access = model('#MenuUrl','adm_')->getMenuByRole ( $user_info ['user_role'] );
	
	foreach ( $data as $k => $module ) {
		$list = model('#MenuUrl','adm_')->getlistByModuleId ($module ['module_id'],'sidebar');
		if (! $list) {
			unset ( $data [$k] );
			continue;
		}
		//去除无权限访问的
		foreach ( $list as $key => $value ) {
			if (! in_array ( $value ['menu_url'], $access )) {
				unset ( $list [$key] );
			}
		}
		$data [$k] ['menu_list'] = $list;
	}
	return $data;
  }


  public function getUserByName($user_name) {
		$sql= "select * ,g.group_name from ".$this->getTableName() ." u,".model('#UserGroup','adm_')->getTableName()." g where u.user_name='$user_name' and u.user_group=g.group_id";
		$list = $this->db->query($sql)->fetch();
		if ($list) {
			$list['login_time']=Common::getDateTime($list['login_time']);
			return $list;
		}
		return array ();
	}
	
	public function getUserById($user_id) {
		if (! $user_id || ! is_numeric ( $user_id )) {
			return false;
		}
		$list = $this->where("user_id={$user_id}")->fetch();
		if ($list) {
			$list['login_time']=Common::getDateTime($list['login_time']);
			return $list;
		}
		return array ();
	}
	
	public function setCookieRemember($uid,$day=7){
		$encrypted = urlencode(Encrypt::encrypt($uid));
		cookie("adm_remember",$encrypted,86400*$day);
	}
	
	public function getCookieRemember(){
		$encrypted = cookie("adm_remember");
		$base64=urldecode($encrypted);
		return Encrypt::decrypt($base64);
	}
	
	public function search($user_group ,$user_name, $start ='' ,$page_size='' ) {
		$limit ="";
		$where = " where 1";
		if($page_size){
			$limit =" limit $start,$page_size ";
		}
		if($user_group >0  && $user_name!=""){
			$where .= " and u.user_group=$user_group and u.user_name like '%$user_name%'";
		}else{
			if($user_group>0){
				$where .= " and u.user_group=$user_group ";
			}
			if($user_name!=""){
				$where .= " and u.user_name like '%$user_name%' ";
			}
		}
		$sql = "select * ,coalesce(g.group_name,'已删除') from ".$this->getTableName()." u left join ".model('#UserGroup','adm_')->getTableName()." g on u.user_group = g.group_id $where order by u.user_id desc $limit";
		
		$result=$this->db->query($sql);
		$list = [];
		while($result->next()){
			$item = $result->get();
			$item['login_time']=Common::getDateTime($item['login_time']);
			$list[] = $item;
		}
		return $list;
	}
	
	public function getUsersByGroup( $group_id ) {
		if(empty($group_id) || !is_numeric($group_id)){
			return array();
		}
		$result = $this->where("user_group={$group_id}")->select();
		foreach($result as &$item){
				$item['login_time'] && $item['login_time']=Common::getDateTime($item['login_time']);
		}
		return $result;
	}
	
	public function checkActionAccess() {
		$action_url = Common::getActionUrl();
		$user_info = session('user_info');
		$role_menu_url = model('#MenuUrl','adm_')->getMenuByRole ( $user_info['user_role']);
		$search_result = in_array ( $action_url, $role_menu_url );
		if ($search_result) {
			return true;
		}
		return false;
	}
	
	public function updateUser($user_id,$user_data) {
		if (! $user_data || ! is_array ( $user_data )) {
			return false;
		}
		if(isset($user_data['password']) && ($user_data['password'] = trim($user_data['password'])) && !empty($user_data['password'])){
			list($password,$salt) = $this->genPassword($user_data['password']);
			$user_data['password'] = $password;
			$user_data['salt'] = $salt;
		}else{
			if(isset($user_data['password']))
				unset($user_data['password']);
			if(isset($user_data['salt']))
				unset($user_data['salt']);
		}
		return $this->where("user_id={$user_id}")->update($user_data);
	}
	
	/**
	* 批量修改用户，如批量修改用户分组
	* user_ids 可以为无key数组，也可以为1,2,3形势的字符串
	*/
	public function batchUpdateUsers($user_ids,$user_data) {
		if (! $user_data || ! is_array ( $user_data )) {
			return false;
		}
		if(!is_array($user_ids)){
			$user_ids=explode(',',$user_ids);
		}
		return $this->where("user_id in(".join(',',$user_ids).")")->update($user_data);
	}
	
	public function addUser($user_data) {
		if (! $user_data || ! is_array ( $user_data )) {
			return false;
		}
		return $this->insert($user_data);
	}
	
	public function delUser($user_id) {
		if (! $user_id || ! is_numeric ( $user_id )) {
			return false;
		}
		return $this->where("user_id={$user_id}")->delete();
	}
	
	public function delUserByUserName($user_name) {
		if (! $user_name ) {
			return false;
		}
		return $this->where("user_name='{$user_name}'")->delete();
	}
	
	public function searchCount($user_group,$user_name) {
		$where = "1";
		if($user_group>0){
			$where .= " and user_group={$user_group}";
		}
		if($user_name!=""){
			$where .= " and user_name like '%{$user_name}%'";
		}
		return $this->where($where)->count();
	}

	public function getQuickNote(){
		$note = model('#QuickNote','adm_')->getRandomNote();
		if($note){
			$note_content=$note['note_content'];
			$note_html="<div class=\"alert alert-info\">
				<button type=\"button\" class=\"close\" data-dismiss=\"alert\">×</button>$note_content</div>";
			return $note_html;
		}
		return '';
	}

	public function isPageEditor($uid){
		if($uid==1)return true;
		$user = $this->getUserById($uid);
		if(empty($user))return false;
		$group = model('#UserGroup','adm_')->getGroupById($user['user_group']);
		if(empty($group) || empty($group['group_role'])) return false;
		$menu = model('#MenuUrl','adm_')->getMenuByUrl('/editWidget');
		if(!in_array($menu['menu_id'], explode(',',$group['group_role'])))return false;
		return true;
	}

	public function getSubdomain(){
		if(session('uid')==1){
			return model('#Subdomain')->search('display=1',0,1000,'sort_order');
		}
		$sub_domain_id = session('user_info')['domain_id'];
		if(empty($sub_domain_id)) return false;
		return model('#Subdomain')->search("id in({$sub_domain_id})",0,1000,'sort_order');
	}

	public function checkDomainPriv($dom_id,$subdomains){
		if(session('uid')==1) return true;
		foreach($subdomains as $sd){
			if($sd['id']==$dom_id) return true;
		}
		return false;
	}
}